//
//  NSChatListViewController.m
//  Meboo
//
//  Created by kyo on 2023/10/16.
//

#import "NSChatListViewController.h"
#import "NSConversationViewController.h"
#import "NSChatListViewController.h"
#import "NSChatListCell.h"
#import "MBChatNavView.h"
#import "NSChatNullView.h"

@interface NSChatListViewController ()
<
UITableViewDelegate,
UITableViewDataSource
>
//背景图
@property (nonatomic, strong) UIImageView *backImageView;
//头部组件
@property (nonatomic, strong) MBChatNavView *chatNavView;
//kefu的信息
@property (nonatomic, strong) RCUserInfo *kefuInfo;
//是否更新了信息
@property (nonatomic, assign) BOOL isUpdate;
//定时刷新在线状态
@property (nonatomic ,strong) NSTimer *onlineTimer;
//所有id的数组
@property (nonatomic ,strong) NSMutableArray *codeArr;
//空视图
@property (nonatomic, strong) NSChatNullView *nullView;
@end

@implementation NSChatListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    //融云父类自带的空视图 比较难用,直接隐藏,使用自定义的空视图
    self.emptyConversationView.alpha = 0;
    [self setupUI];
    //获取客服信息
    [self getKefuInfo];
    //定时器启动轮循 获取在线和fc信息
    
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    //获取用户信息---icon/name
    if (!self.isUpdate) {
        [self getRCUserInfo];
    }
    [self reloadOnline];
    [self.onlineTimer fire];
}

//页面即将消失
- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    [self.onlineTimer invalidate];
    self.onlineTimer = nil;
}

//是否空数据判定 并刷新
- (void)nullViewSetNullArr {
    __WeakSelf
    //以下操作必须在主线程!!!
    dispatch_async(dispatch_get_main_queue(), ^{
        [weakSelf.conversationListTableView reloadData];
        if (weakSelf.conversationListDataSource.count == 0) {
            weakSelf.conversationListTableView.hidden = YES;
            weakSelf.nullView.hidden = NO;
        } else {
            weakSelf.conversationListTableView.hidden = NO;
            weakSelf.nullView.hidden = YES;
        }
    });
}

#pragma mark -- 定时刷新在线状态 && fc数据
- (void)reloadOnline {
    if (self.codeArr.count == 0) {
        [self getCodeArrAfterLoad];
    }
    __WeakSelf
    
    //flashchat && online数据处理
    [[MBChatDataManager sharedManager] getChatListFCInfo:^(BOOL success) {
        if (success) {
            for (int i = 0; i<weakSelf.conversationListDataSource.count; i++) {
                RCConversationModel *conModel = weakSelf.conversationListDataSource[i];
                NSMutableDictionary *dict = [conModel.extend isKindOfClass:[NSDictionary class]] ? conModel.extend : [NSMutableDictionary dictionary];
                if ([[MBChatDataManager sharedManager].fcCodeArr containsObject:conModel.targetId]) {
                    //fc
                    [dict setValue:@"1" forKey:@"flashchat"];
                } else {
                    //非fc
                    [dict setValue:@"0" forKey:@"flashchat"];
                }
                
                if ([[MBChatDataManager sharedManager].onlineCodeArr containsObject:conModel.targetId]) {
                    //在线
                    [dict setValue:@"1" forKey:@"online"];
                } else {
                    //离线
                    [dict setValue:@"0" forKey:@"online"];
                }
                conModel.extend = dict;
                [weakSelf.conversationListDataSource replaceObjectAtIndex:i withObject:conModel];
            }
            [weakSelf nullViewSetNullArr];
        }
    }];
}

//code数组 数据处理
- (void)getCodeArrAfterLoad {
    [self.codeArr removeAllObjects];
//    for (MBChatNewFriendsModel *model in [MBChatDataManager sharedManager].newFriendsDataArr) {
//        [self.codeArr addObject:model.userCode];
//    }
    for (RCConversationModel *model in self.conversationListDataSource) {
        [self.codeArr addObject:model.targetId];
    }
}

#pragma mark - Private Method
//从融云获取用户信息 ---- 使用调度组,全部信息加载之后统一刷新, 防止频繁刷新造成的闪烁
- (void)getRCUserInfo {
    __WeakSelf
    dispatch_queue_t queue = dispatch_queue_create("queue", DISPATCH_QUEUE_CONCURRENT);
    dispatch_group_t group = dispatch_group_create();
    
    //循环进出组
    for (RCConversationModel *model in self.conversationListDataSource) {
        RCUserInfo *userInfo = [[RCIM sharedRCIM] getUserInfoCache:model.targetId];
        if (userInfo.portraitUri.length == 0) {
            weakSelf.isUpdate = YES;
            dispatch_group_enter(group);
            dispatch_group_async(group, queue, ^{
                [[MBChatDataManager sharedManager] getUserInfoWithUserId:model.targetId completion:^(RCUserInfo * _Nonnull userInfo) {
                    [[RCIM sharedRCIM] refreshUserInfoCache:userInfo withUserId:model.targetId];
                    dispatch_group_leave(group);
                }];
            });
        }
    }
    
    //调度组 全部加载完成之后的回调
    dispatch_group_notify(group, queue, ^{
        if (weakSelf.isUpdate) {
            [weakSelf nullViewSetNullArr];
        }
    });
    
    //自己的信息也加载一遍  无需进组,因为不参与本页面刷新 在下个页面会用到
    RCUserInfo *meInfo = [[RCIM sharedRCIM] getUserInfoCache:[MBUserAccount defaultAccount].chatUserId];
    if (meInfo.portraitUri.length == 0) {
        [[MBChatDataManager sharedManager] getUserInfoWithUserId:[MBUserAccount defaultAccount].chatUserId completion:^(RCUserInfo * _Nonnull userInfo) {
            [[RCIM sharedRCIM] refreshUserInfoCache:userInfo withUserId:[MBUserAccount defaultAccount].chatUserId];
        }];
    }
}

//获取客服相关信息
- (void)getKefuInfo {
    if ([MBUserAccount defaultAccount].kefuTargetId.length > 0) {
        self.kefuInfo = [[RCIM sharedRCIM] getUserInfoCache:[MBUserAccount defaultAccount].kefuTargetId];
        return;
    }
    __WeakSelf
    [[MBChatDataManager sharedManager] getChatKefuUrl:^(RCUserInfo * _Nonnull userInfo) {
        if (userInfo) {
            weakSelf.kefuInfo = userInfo;
            [[RCIM sharedRCIM] refreshUserInfoCache:userInfo withUserId:userInfo.userId];
            MBUserAccount  *account = [MBUserAccount defaultAccount];
            account.kefuTargetId = userInfo.userId;
            [MBUserAccount saveAccount:account];
            
            NSMutableArray *arr = [NSMutableArray arrayWithArray:self.conversationListDataSource];
            for (RCConversationModel *model in arr) {
                if ([model.targetId isEqualToString:userInfo.userId]) {
                    [self.conversationListDataSource removeObject:model];
                }
            }
            [weakSelf nullViewSetNullArr];
        }
    }];
}

//消息点击事件 ---> 进入单聊页面
- (void)onSelectedTableRow:(RCConversationModelType)conversationModelType
         conversationModel:(RCConversationModel *)model
               atIndexPath:(NSIndexPath *)indexPath {
    //model.targetId
    NSConversationViewController *conversationVC = [[NSConversationViewController alloc] initWithConversationType:ConversationType_PRIVATE targetId:model.targetId];
    conversationVC.isFromList = YES;
//    //fc状态标识符的判断
//    if ([model.extend isKindOfClass:[NSDictionary class]]) {
//        if ([[model.extend valueForKey:@"flashchat"] isEqualToString:@"1"]) {
//            conversationVC.isFlashChat = YES;
//        }
//    }
    
//    [[MBChatDataManager sharedManager] getUserMessageNumWithUserCode:model.targetId type:1 success:^(BOOL success) {
//        if (success) {
//            conversationVC.isMatched = [MBChatDataManager sharedManager].isMatched;
//            [self.navigationController pushViewController:conversationVC animated:YES];
//        }
//    }];
    
    conversationVC.sendMessageBlock = ^(NSInteger sendedNum) {
        [[MBChatDataManager sharedManager] getUserMessageNumWithUserCode:model.targetId type:2 success:^(BOOL success) {
        }];
    };
    [self.navigationController pushViewController:conversationVC animated:YES];
    /**
     埋点
     点击会话IM_Chat
     */
    [[NSIOApiManager sharedManager] setIOWithEventName:@"IM_Chat"];
}

//左滑删除的动画 贝塞尔曲线绘制 注意开始点,结束点,旋转角度,动画时长
- (void)showAddCartAnmationSview:(UIView *)sview
                       imageView:(UIView *)imageView
                        starPoin:(CGPoint)startPoint
                        endPoint:(CGPoint)endpoint
                     dismissTime:(float)dismissTime
{
    __block CALayer *layer;
    layer                               = [[CALayer alloc]init];
    layer.contents                      = imageView.layer.contents;
    layer.frame                         = imageView.frame;
    layer.opacity                       = 1;
    [sview.layer addSublayer:layer];
    UIBezierPath *path                  = [UIBezierPath bezierPath];
    [path moveToPoint:startPoint];
    [path addQuadCurveToPoint:endpoint controlPoint:startPoint];
    //设置位置动画
    CAKeyframeAnimation *animation=[CAKeyframeAnimation animationWithKeyPath:@"position"];
    animation.path                      = path.CGPath;
    animation.removedOnCompletion       = NO;
    //设置大小动画
    CGSize finalSize                    = CGSizeMake(imageView.bounds.size.height, imageView.bounds.size.width);
    CABasicAnimation *resizeAnimation   = [CABasicAnimation animationWithKeyPath:@"bounds.size"];
    resizeAnimation.removedOnCompletion = NO;
    [resizeAnimation setToValue:[NSValue valueWithCGSize:finalSize]];
    //旋转
    CABasicAnimation* rotationAnimation;
    rotationAnimation                   = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
    rotationAnimation.toValue           = [NSNumber numberWithFloat: M_PI * 2.0 ];
    rotationAnimation.cumulative        = YES;
    rotationAnimation.duration          = 300000;
    rotationAnimation.repeatCount       = 1000;
    //动画组
    CAAnimationGroup * animationGroup   = [[CAAnimationGroup alloc] init];
//    animationGroup.animations           = @[animation,resizeAnimation,rotationAnimation];
    animationGroup.animations           = @[animation];
    animationGroup.duration             = dismissTime;
    animationGroup.removedOnCompletion  = NO;
    animationGroup.fillMode             = kCAFillModeForwards;
    animationGroup.autoreverses         = NO;
    animationGroup.timingFunction       = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn];
    [layer addAnimation:animationGroup forKey:@"buy"];
    
    //动画结束 移除layer
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(dismissTime * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [layer removeFromSuperlayer];
        layer = nil;
    });
}

//view转图片
- (UIImageView*)convertViewToImage:(UIView*)view {
    CGSize s = view.bounds.size;
    // 下面方法，第一个参数表示区域大小。第二个参数表示是否是非透明的。如果需要显示半透明效果，需要传NO，否则传YES。第三个参数就是屏幕密度了
    UIGraphicsBeginImageContextWithOptions(s, NO, [UIScreen mainScreen].scale);
    [view.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage*image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    UIImageView *imageView = [UIImageView new];
    imageView.frame = view.frame;
    imageView.image = image;
    return imageView;
}

#pragma mark -- tableView  delegate datasource
//融云方法获取数据数组 --- 注意dataSource是新增的数据,不是总数据
- (NSMutableArray *)willReloadTableData:(NSMutableArray *)dataSource {
    NSMutableArray * dataArr = [NSMutableArray array];
    for (RCConversationModel *model in dataSource) {
        model.conversationModelType = RC_CONVERSATION_MODEL_TYPE_CUSTOMIZATION;
        if (![model.targetId isEqualToString:[MBUserAccount defaultAccount].kefuTargetId]) {
            
            NSMutableDictionary *dict = [model.extend isKindOfClass:[NSDictionary class]] ? model.extend : [NSMutableDictionary dictionary];
            if ([[MBChatDataManager sharedManager].fcCodeArr containsObject:model.targetId]) {
                //fc
                [dict setValue:@"1" forKey:@"flashchat"];
            } else {
                //非fc
                [dict setValue:@"0" forKey:@"flashchat"];
            }
            
            if ([[MBChatDataManager sharedManager].onlineCodeArr containsObject:model.targetId]) {
                //在线
                [dict setValue:@"1" forKey:@"online"];
            } else {
                //离线
                [dict setValue:@"0" forKey:@"online"];
            }
            model.extend = dict;
            [dataArr addObject:model];
        }
    }
    if (dataArr.count == 0) {
        [self nullViewSetNullArr];
    }
    return dataArr;
}

//cell数据处理
- (RCConversationBaseCell *)rcConversationListTableView:(UITableView *)tableView
                                  cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSChatListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"NSChatListCell"];
    if (!cell) {
        cell = [[NSChatListCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"NSChatListCell"];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    RCConversationModel *model = self.conversationListDataSource[indexPath.row];
    cell.model = model;
    cell.layer.cornerRadius = MBHeightScale(10);
    cell.clipsToBounds = YES;
    return cell;
}

////侧滑删除
//- ( UISwipeActionsConfiguration *)tableView:(UITableView *)tableView trailingSwipeActionsConfigurationForRowAtIndexPath:(NSIndexPath *)indexPath {
//    __WeakSelf
//    //删除
//    UIContextualAction *deleteRowAction = [UIContextualAction contextualActionWithStyle:UIContextualActionStyleDestructive title:@"Delete" handler:^(UIContextualAction * _Nonnull action, __kindof UIView * _Nonnull sourceView, void (^ _Nonnull completionHandler)(BOOL)) {
////        [weakSelf deleteNotice:model];
//    }];
//    deleteRowAction.backgroundColor = HEXS(@"FE6565");
//    deleteRowAction.image = ImageWithName(@"chat_list_delete");
//    deleteRowAction.title = @"Delete";
//    
//    UISwipeActionsConfiguration *config = [UISwipeActionsConfiguration configurationWithActions:@[deleteRowAction]];
//    config.performsFirstActionWithFullSwipe = NO;
//    return config;
//}

//// 自定义 cell
//- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
//    
//    MBChatListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MBChatListCell"];
//    if (!cell) {
//        cell = [[MBChatListCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"MBChatListCell"];
//    }
//    cell.selectionStyle = UITableViewCellSelectionStyleNone;
//    cell.model = self.dataArr[indexPath.row];
////    __WeakSelf
////    cell.rightButtons = @[[MGSwipeButton buttonWithTitle:@"" icon:[UIImage imageNamed:@"chat_conversion_delete"] backgroundColor:HEXS(@"FF4545") callback:^BOOL(MGSwipeTableCell * _Nonnull cell) {
////        // 删除按钮
////        CGFloat height = ScreenHeight -(ScreenHeight - MBHeightScale(192)-StatusBarAndNavigationBarHeight)/2;
////
////        CGRect rectInTableView = [tableView rectForRowAtIndexPath:indexPath];//获取cell在tableView中的位置
////        CGRect rectInSuperview = [tableView convertRect:rectInTableView toView:[tableView superview]];
////        cell.frame = rectInSuperview;
////        
////        UIView *view = weakSelf.view;
////        UIImageView *imageView = [weakSelf convertViewToImage:cell];
////        CGPoint startPoint = CGPointMake(ScreenWidth/2, cell.frame.origin.y+cell.frame.size.height/2);
////        
////        
////        CGPoint endPoint = CGPointMake(-MBHeightScale(225), height);
////        
////        
////        // 删除按钮
////        [weakSelf showAddCartAnmationSview:view imageView:imageView starPoin:startPoint endPoint:endPoint dismissTime:0.5];
////        [self.dataArr removeObjectAtIndex:indexPath.row];
////        [self.conversationListTableView reloadData];
////        return YES;
////    }]];
////    cell.rightSwipeSettings.transition = MGSwipeTransitionDrag;
//    cell.layer.cornerRadius = MBHeightScale(10);
//    cell.clipsToBounds = YES;
//    return cell;
//}


// 高度
- (CGFloat)rcConversationListTableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return MBHeightScale(76);
}

//左滑删除回调
- (void)rcConversationListTableView:(UITableView *)tableView
                 commitEditingStyle:(UITableViewCellEditingStyle)editingStyle
                  forRowAtIndexPath:(NSIndexPath *)indexPath {
    __WeakSelf
        RCConversationModel *model = self.conversationListDataSource[indexPath.row];
    [[RCCoreClient sharedCoreClient] removeConversation:model.conversationType targetId:model.targetId completion:^(BOOL ret) {
        if (ret) {
            [weakSelf.conversationListDataSource removeObjectAtIndex:indexPath.row];
            [weakSelf nullViewSetNullArr];
        }
    }];
    
    //计算动画起始位置 和动画组所需参数
    CGFloat height = ScreenHeight -(ScreenHeight - MBHeightScale(192)-StatusBarAndNavigationBarHeight)/2;
    NSChatListCell *cell = [self.conversationListTableView cellForRowAtIndexPath:indexPath];
    CGRect rectInTableView = [tableView rectForRowAtIndexPath:indexPath];//获取cell在tableView中的位置
    CGRect rectInSuperview = [tableView convertRect:rectInTableView toView:[tableView superview]];
    cell.frame = rectInSuperview;
    
    UIView *view = weakSelf.view;
    UIImageView *imageView = [weakSelf convertViewToImage:cell];
    CGPoint startPoint = CGPointMake(ScreenWidth/2, cell.frame.origin.y+cell.frame.size.height/2);
    CGPoint endPoint = CGPointMake(-225, height);
    [weakSelf showAddCartAnmationSview:view imageView:imageView starPoin:startPoint endPoint:endPoint dismissTime:0.5];
    /**
     埋点
     点击删除会话IM_Chat
     */
    [[NSIOApiManager sharedManager] setIOWithEventName:@"IM_Deletechat"];
}

- (void)dealloc
{
    //页面即将消失---离开此页面 刷新全局消息未读数
    MBUserAccount  *account = [MBUserAccount defaultAccount];
    [[RCCoreClient sharedCoreClient] getTotalUnreadCountWith:^(int unreadCount) {
        [[RCCoreClient sharedCoreClient] getUnreadCount:ConversationType_PRIVATE targetId:[MBUserAccount defaultAccount].kefuTargetId completion:^(int count) {
            dispatch_async(dispatch_get_main_queue(), ^{
                account.unReadNum = unreadCount-count;
                [MBUserAccount  saveAccount:account];
                [[NSNotificationCenter defaultCenter] postNotificationName:UPDATE_MESSAGE_UNREAD object:nil];
            });
        }];
    }];

}

#pragma mark - UI
- (void)setupUI {
    [self.view addSubview:self.backImageView];
    [self.view sendSubviewToBack:self.backImageView];
    [self.backImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    
    [self.view addSubview:self.chatNavView];
    [self.chatNavView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.equalTo(self.view);
        make.height.mas_equalTo(StatusBarAndNavigationBarHeight);
    }];
    
    self.conversationListTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.conversationListTableView.showsVerticalScrollIndicator = NO;
    self.conversationListTableView.backgroundColor = UIColor.clearColor;
//    self.conversationListTableView.frame = CGRectMake(MBHeightScale(20), MBHeightScale(192)+StatusBarAndNavigationBarHeight, ScreenWidth-MBHeightScale(40), ScreenHeight-StatusBarAndNavigationBarHeight-MBHeightScale(192));
    
    [self.conversationListTableView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.bottom.left.right.equalTo(self.view);
        make.top.equalTo(self.chatNavView.mas_bottom).offset(MBHeightScale(10));
    }];
    
    [self.view addSubview:self.nullView];
    [self.nullView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.chatNavView.mas_bottom).offset(MBHeightScale(0));
        make.left.right.equalTo(self.view);
        make.bottom.equalTo(self.view);
    }];
}

#pragma mark - Setter && Getter

- (MBChatNavView *)chatNavView {
    if (!_chatNavView) {
        _chatNavView = [MBChatNavView new];
    }
    return _chatNavView;
}

- (NSTimer *)onlineTimer {
    if (!_onlineTimer) {
        _onlineTimer = [NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(reloadOnline) userInfo:nil repeats:YES];
    }
    return _onlineTimer;
}

- (NSMutableArray *)codeArr {
    if (!_codeArr) {
        _codeArr = [NSMutableArray array];
    }
    return _codeArr;
}

- (UIImageView *)backImageView {
    if (!_backImageView) {
        _backImageView = [UIImageView new];
        _backImageView.image = ImageWithName(@"chat_back_image");
    }
    return _backImageView;
}

- (NSChatNullView *)nullView {
    if (!_nullView) {
        _nullView = [NSChatNullView new];
    }
    return _nullView;
}
@end
